package com.dl.exam.servlet.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 用户类操作
 * @author DL
 * @create 2022-1-29 16:37:00
 */
public class UserController extends HttpServlet {

  /*  @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String method = req.getParameter("method");
        //System.out.println("method = " + method);
        if (method == null){
            method = "";
        }
        switch (method){
            case "" :
                test(req, resp);
                break;
            case "startExam" :
                startExam(req, resp);
                break;
            case "getExam" :
                queryUnfinishedExam(req, resp);
                break;
            case "submitExam" :
                submitExam(req, resp);
                break;
            case "all" :
                queryAllExam(req, resp);
                break;
            case "queryFinishedExam" :
                queryFinishedExam(req, resp);
                break;
            default :
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        doGet(req, resp);
    }

    UserService userService = new UserServiceImpl();


    //查询用户已完成的考试信息和答案
    private void queryFinishedExam(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String exam_id = req.getParameter("exam_id");
        int exam_type = Integer.parseInt(req.getParameter("exam_type"));
        int currentPage = Integer.parseInt(req.getParameter("currentPage"));
        Page<Question> questionPage = userService.queryFinishedExam(exam_id, exam_type, currentPage, 20);

        PrintWriter writer = resp.getWriter();
        System.out.println("questionPage = " + questionPage);
        writer.write(JSON.toJSONString(questionPage));
    }

    //查询用户所有的考试
    private void queryAllExam(HttpServletRequest req, HttpServletResponse resp) throws IOException {
*//*        HttpSession session = req.getSession();
        User user = (User) session.getAttribute(Info.USER_INFO.getValue());*//*
        User user = (User) req.getAttribute("user");

        String user_id = user.getUser_id();//获得用户名

        String currentPage = req.getParameter("currentPage");

        Page<Exam> examPage = userService.queryAllExam(user_id, Integer.parseInt(currentPage), 20);

        String string = JSONArray.toJSONString(examPage);
        System.out.println(this.getClass().getSimpleName() + " string = " + string);
        PrintWriter writer = resp.getWriter();
        writer.write(string);
    }

    //提交考试
    private void submitExam(HttpServletRequest req, HttpServletResponse resp) throws IOException {
*//*        HttpSession session = req.getSession();
        User user = (User) session.getAttribute(Info.USER_INFO.getValue());*//*
        User user = (User) req.getAttribute("user");

        String user_id = user.getUser_id();//获得用户名

        List<HashMap<String, Object>> listMap = userService.queryUnfinishedExamAnswer(user_id);//获得本次考试试题的答案
        System.out.println("listMap = " + listMap);

        JSONObject parse = JsonUtils.parse(req);//解析json
        JSONArray questions = parse.getJSONArray("questions");//转为json数组
        List<Question> questionList = questions.toJavaList(Question.class);//转为集合
        System.out.println("questionList = " + questionList);

        ArrayList<String> paramsList = new ArrayList<>();
        questionList.forEach(question -> {
            paramsList.add(question.getQuestion_id());
            paramsList.add(question.getAnswer());
        });
        String[] params = paramsList.toArray(new String[]{});
        System.out.println("params = " + Arrays.toString(params));

*//*        List<Object> test = listMap.stream().map(map -> map.get("question_id"))
                .filter(question_id -> questionList.stream()
                        .noneMatch(question -> question.getQuestion_id().equals(question_id)))
                .collect(Collectors.toList());*//*
        AtomicReference<Float> totalScore = new AtomicReference<>((float) 0);//试卷总分
        AtomicReference<Float> userScore = new AtomicReference<>((float) 0);//用户得分

        List<HashMap<String, Object>> collect = listMap.stream()//流式操作
                .peek(map -> {
                    totalScore.set(totalScore.get() + (float) map.get("score"));//累加每个题的分值
                }).filter(map -> {//过滤，判断用户答案是否正确
                    boolean flag = false;//是否命中; 0：未命中  >0：命中
                    for (int i = 0; i < questionList.size(); i++) {
                        if (map.get("question_id").equals(questionList.get(i).getQuestion_id())) {//使用试题id匹配题目
                            if (map.get("answer").equals(questionList.get(i).getAnswer())) {//匹配答案
                                userScore.set(userScore.get() + (float) map.get("score"));//累加正确题目的分值
                                flag = true;
                            }
                            questionList.remove(i);
                            //System.out.println("questionList.size() = " + questionList.size());
                        }
                    }
                    return flag;//如果返回值为true，则将该元素交给下一个Stream流环节
                }).collect(Collectors.toList());

*//*        List<Question> collect = questionList.stream()
                .peek(question -> {
                    String question_id = question.getQuestion_id();
                    String answer = question.getAnswer();
                }).filter(question -> {
                    boolean flag = false;//是否命中; 0：未命中  >0：命中
                    listMap.stream().filter(map -> {
                        if (map.get("question_id").equals(question.getQuestion_id())) {//使用试题id匹配题目
                            if (map.get("answer").equals(question.getAnswer())) {//匹配答案
                                System.out.println("map.get(\"answer\") = " + map.get("answer"));
                                System.out.println("question.getAnswer() = " + question.getAnswer());
                                userScore.set(userScore.get() + (float) map.get("score"));
                                return true;
                            }
                        }
                        return false;
                    });
                    return true;
                }).collect(Collectors.toList());*//*

        System.out.println("totalScore = " + totalScore);
        System.out.println("userScore = " + userScore);
        System.out.println("collect = " + collect);

        //分数计算完毕，更新数据库中的考试信息
        String exam_id = userService.queryUnfinishedExamId(user_id);

        PrintWriter writer = resp.getWriter();
        if (exam_id != null){
            //更新考试信息表(更新答案)
            boolean updateExamAnswer = userService.updateExamAnswer(exam_id, params);
            //更新考试管理表
            boolean updateExamManage = userService.updateExamManage(user_id, userScore.get(), totalScore.get());
            if (updateExamAnswer && updateExamManage){
                writer.write(String.valueOf(true));
            }
        }else {
            writer.write(String.valueOf(false));

        }
    }

    @Test
    public void testForEach(){
        ArrayList<Object> list = new ArrayList<>();
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("question_id","c1941a540e");
        map1.put("answer","C");
        map1.put("score",1.5);
        HashMap<String, Object> map2 = new HashMap<>();
        map2.put("question_id","c1941a540e");
        map2.put("answer","C");
        map2.put("score",1.5);
    }

    //region 查询用户未完成的考试
    private void queryUnfinishedExam(HttpServletRequest req, HttpServletResponse resp) throws IOException {
*//*        HttpSession session = req.getSession();
        User user = (User) session.getAttribute(Info.USER_INFO.getValue());*//*
        User user = (User) req.getAttribute("user");
        String user_id = user.getUser_id();
        System.out.println("user_id = " + user_id);

        String currentPage = req.getParameter("currentPage");
        System.out.println("currentPage = " + currentPage);

        //查询到的试题
        //List<Question> questions = (List<Question>) userService.queryUnfinishedExam(user_id, Integer.parseInt(currentPage), 10);
        List<Object> questions = (List<Object>) userService.queryUnfinishedExam(user_id, Integer.parseInt(currentPage), 10);

        PrintWriter writer = resp.getWriter();
        writer.write(JSON.toJSONString(questions));//返回查询结果，给前端控制页面跳转
    }
    //endregion

    //region 开始考试
    private void startExam(HttpServletRequest req, HttpServletResponse resp) throws IOException {
*//*        HttpSession session = req.getSession();
        User user = (User) session.getAttribute(Info.USER_INFO.getValue());*//*
        User user = (User) req.getAttribute("user");

        System.out.println("user.getUser_id() = " + user.getUser_id());

        int state = 0;
        boolean existExam = userService.existExam(user.getUser_id());//查询是否存在考试
        System.out.println("existExam = " + existExam);
        if (existExam){
            //存在考试，不能新增考试
            System.out.println("存在考试，不能新增考试");
        }else {
            //可以考试,解析json
            JSONObject parse = JsonUtils.parse(req);
            System.out.println("parse = " + parse);
            JSONObject form = parse.getJSONObject("form");
            int radio = form.getInteger("radio");//问题类型
            String subject = form.getString("select");//科目
            int degree = form.getInteger("rate");//难度
            int total = form.getInteger("slider");//数量

            boolean flag = false;//判断查询是否成功，默认false
            Page<?> questionPage = null;
            switch (radio){//判断考试类型
                case 1 ://单选题考试
                    SingleServiceImpl singleService = new SingleServiceImpl();
                    questionPage = singleService.queryExam(subject, degree, 1, total);
                    break;
                case 2 ://判断题考试
                    break;
                case 3 ://主观题考试
                    SubjectiveServiceImpl subjectiveService = new SubjectiveServiceImpl();
                    questionPage = subjectiveService.queryByCondition(subject, degree, 1, total);
                    break;
            }

            System.out.println("questionPage = " + questionPage);
            if (questionPage != null && questionPage.getTotalPage() != 0){
                //判断查询是否成功，题目数量是否足够等
                flag = true;
            }

            if (flag) {//如果查到题目，则可以开始考试
                String exam_id = UUIDUtils.getUUID10();//随机uuid作为考试id
                String user_id = user.getUser_id();
                userService.startExam(exam_id, user_id, radio);//向考试管理表写入信息，考试id，用户id，考试类型

                List<Question> questions = (List<Question>) questionPage.getList();

                String[] strings = new String[questions.size()];
                for (int i = 0; i < questions.size(); i++) {
                    strings[i] = questions.get(i).getQuestion_id();//获得试题id
                }
                System.out.println("strings = " + Arrays.toString(strings));

                userService.addExamInfo(exam_id, strings);//向考试信息表写入信息

                //题目信息放入session
                //session.setAttribute(Info.SESSION_EXAM.getValue(), JSON.toJSONString(questionPage));
                state = 1;
            }else {
                System.out.println("题目信息有误，试题可能不够等");
                state = 2;
            }
        }
        PrintWriter writer = resp.getWriter();
        writer.write(JSON.toJSONString(state));//返回查询结果，给前端控制页面跳转
    }
    //endregion

    private void test(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //resp.sendRedirect("/user/test.jsp");
        String string = JSONArray.toJSONString("/user/test.jsp");
        PrintWriter writer = resp.getWriter();
        writer.write(string);
*//*        String currentPage = req.getParameter("currentPage");
        //System.out.println("currentPage = " + currentPage);
        SingleServiceImpl singleService = new SingleServiceImpl();

        Page<SingleQuestion> list = singleService.query(Integer.parseInt(currentPage), 5);

        //System.out.println("list = " + list);
        String string = JSONArray.toJSONString(list);
        PrintWriter writer = resp.getWriter();
        writer.write(string);*//*
    }
*/
}
